<template>
    <div class="workorder">
        <div class="page-head">
            <span class="head-text">机加工报工</span>
            <span class="head-text">当前用户：{{ userInfo.username }}</span>
        </div>
        <div class="page-radio">
            <div class="radio-info">
                <el-checkbox v-model="isPlanShutdown">计划停机请勾选</el-checkbox>
            </div>
            <div class="radio-head">
                <el-radio-group v-model="workShop">
                    <el-radio :label="1">机加工</el-radio>
                    <el-radio :label="2">走心机</el-radio>
                </el-radio-group>
            </div>
            <div class="radio-content" v-show="workShop === 1">
                <span class="content-tip">工序</span>
                <div class="content-process">
                    <el-radio-group v-model="workShopProcess">
                        <el-radio :label="2" class="process-item">热处理</el-radio>
                        <el-radio :label="3" class="process-item">车床</el-radio>
                        <el-radio :label="4" class="process-item">铣床</el-radio>
                        <el-radio :label="7" class="process-item">倒角</el-radio>
                        <el-radio :label="5" class="process-item">清洗机</el-radio>
                    </el-radio-group>
                </div>
            </div>
        </div>
        <div class="page-main">
            <div class="main-left">
                <el-form :model="formData" ref="leftForm" :rules="formDataRules" label-width="110px" label-position="left" size="mini" :hide-required-asterisk="false" class="demo-ruleForm">
                    <el-form-item label="设备" prop="equipment" class="form-item">
                        <el-select v-model="formData.equipment" remote filterable :remote-method="findEquipmentByDeviceCode" clearable placeholder="下拉选择设备" size="small" transfer="true" :popper-append-to-body="false">
                            <el-option v-for="(item,index) in formData.equipmentList" :label="item.deviceCode" :value="item.deviceCode" :key="index"></el-option>
                        </el-select>
                        <icon-svg name="sweep" width="25px" height="25px" color="" style="cursor:pointer;margin-left:1vw;" @click.native="sweep_btn('equipment')"></icon-svg>
                    </el-form-item>
                    <el-form-item label="品号" prop="materialCode">
                        <el-select v-model="formData.materialCode" filterable clearable placeholder="下拉选择产品" size="small" transfer="true" :popper-append-to-body="false" :disabled="isPlanShutdown">
                            <el-option v-for="(item,index) in formData.materialList" :label="item.materialCode" :value="item.materialCode" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="订单" prop="productOrder">
                        <el-select v-model="formData.productOrder" placeholder="下拉选择订单" size="small" :disabled="isPlanShutdown">
                            <el-option v-for="item,index in productOrderList" :label="item.productOrderNumber" :value="item.productOrderNumber" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="完成数量" prop="finishedNum">
                        <el-input v-model="formData.finishedNum" @input="formData.finishedNum = String(formData.finishedNum).replace(/[^\d]/g, '')" size="small" placeholder="请输入完成数量" :disabled="isPlanShutdown"></el-input>
                    </el-form-item>
                    <el-form-item label="不合格数" prop="unQualifiedNum" size="small">
                        <el-input v-model="formData.unQualifiedNum" @input="formData.unQualifiedNum = String(formData.unQualifiedNum).replace(/[^\d]/g, '')" size="small" placeholder="请输入不合格数量" :disabled="isPlanShutdown"></el-input>
                    </el-form-item>
                    <el-form-item label="合格数量" size="small">
                        <el-input :value="qualifiedNum"  placeholder="自动计算" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="计划数量" size="small">
                        <el-input :value="formData.planNumber" placeholder="自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="作业员" size="small">
                        <el-input :value="userInfo.username" placeholder="自动读取当前用户" :disabled="true"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-right">
                <el-form :model="formData" ref="rightForm" :rules="formDataRules" label-width="110px" label-position="left" size="mini" :hide-required-asterisk="false" class="demo-ruleForm">
                    <el-form-item label="工废数量" prop="" size="small">
                        <el-input-number v-model="formData.scrapField1" :min="0" placeholder="请输入工废数量"></el-input-number>
                    </el-form-item>
                    <!-- <el-form-item label="工废原因" prop="">
                        <el-select v-model="formData.scrapField1Reason" placeholder="下拉选择原因" size="small">
                            <el-option v-for="item in wasteList_gf" :label="item" :value="item" :key="item"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="料废数量" prop="" size="small">
                        <el-input-number v-model="formData.scrapField2" :min="0" placeholder="请输入料废数量"></el-input-number>
                    </el-form-item>
                    <!-- <el-form-item label="料废原因" prop="">
                        <el-select v-model="formData.scrapField2Reason" placeholder="下拉选择原因" size="small">
                            <el-option v-for="item in wasteList_lf" :label="item" :value="item" :key="item"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="班次" prop="classes">
                        <el-select v-model="formData.classes" placeholder="下拉选择班次" size="small" disabled>
                            <el-option v-for="item,index in formData.classesList" :label="item.shiftType" :value="item.shiftType" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工时" prop="attendanceHours" size="small">
                        <el-input v-model="formData.attendanceHours" @input="validateInput('attendanceHours')" placeholder="请输入出勤工时" :disabled="isPlanShutdown"></el-input>
                    </el-form-item>
                    <el-form-item label="报工日期" prop="datetime" size="small">
                        <el-date-picker v-model="formData.datetime" :editable="false" value-format="yyyy-MM-dd" type="date" size="small" placeholder="选择日期时间" class="el-date-picker"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="设备运行时长" prop="equipmentRunningHours" size="small">
                        <el-input v-model="formData.equipmentRunningHours" @input="validateInputEquipmentRunningHours" placeholder="请输入设备运行时长(H)" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="停机信息">
                        <el-button plain type="primary" @click="wirteDowntReason" :disabled="isPlanShutdown">{{ downtReasonBtnInfo }}</el-button>
                        <downt-reason ref="downtReason" @close="downtReasonClose"></downt-reason>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="page-footer">
            <el-button type="primary" size="small" class="footer-btn" @click="cancel_btn">取消</el-button>
            <el-button type="primary" size="small" class="footer-btn" :loading="confirmButtonLoading" @click="save_btn">{{ workreportButtonText }}</el-button>
        </div>
    </div>
</template>
  
<script>
import { reqUserInfo, reqProductOrderOfDay, reqProductOrderList, getDeviceAPI,reqDeviceInfo, reqSaveData, reqClassesList, reqMaterialsInfo, reqMaterialInfoAndProductInfoByGid, reqWareHouseInfo, reqClassTeamList, reqOrderResidueCount,reqUserClassInfo } from "@/api/workOrder.js";
import { reqCheckIsTeam } from "@/api/workOrder.js";
import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
import { qrCode } from "@/utils/jingzhi.js";
import DowntReason from "@/components/downtReason/index.vue";
import { reqDefaultSalary,reqOeeInfoByProductModel } from "@/api/meterTable.js";
import { getUserInfoByToken } from "@/utils/toosls.js";
import { Dialog } from "vant";
export default {
    name:"workorder2",
    components:{
        DowntReason
    },
    data() {
        const validateFinishedNum = (rule, value, callback) => {
            const isPlanShutdown = this.isPlanShutdown;
            let unQualifiedNum = this.formData.unQualifiedNum;
            const planNumber = this.formData.planNumber;
            if(!isPlanShutdown){
                if (value === '') {
                    callback(new Error('请输入完成数量'));
                } else if (parseInt(value < 0)) {
                    callback(new Error('输入的数量非法'));
                } else if (parseInt(value) > parseInt(planNumber)) {
                    callback(new Error('输入的完成数量不能大于计划数量'));
                }else if(unQualifiedNum !== '' && parseInt(value) < parseInt(unQualifiedNum)){
                    callback(new Error('完成数量不能小于不合格数量'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validateUnQualifiedNum = (rule, value, callback) => {
            const isPlanShutdown = this.isPlanShutdown;
            let finishedNum =  this.formData.finishedNum;
            if(!isPlanShutdown){
                if (value === '') {
                    callback(new Error('请输入不合格数量'));
                } else if (parseInt(value < 0)) {
                    callback(new Error('输入的不合格数量非法'));
                } else if(finishedNum !== '' && parseInt(value) > parseInt(finishedNum)){
                    callback(new Error('输入的不合格数量不能大于完成数量'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validateMaterialCode = (rule,value,callback) => {
            const isPlanShutdown = this.isPlanShutdown;
            if(!isPlanShutdown){
                if (value === '') {
                    callback(new Error('请选择产品'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validateProductOrder = (rule,value,callback) => {
            const isPlanShutdown = this.isPlanShutdown;
            if(!isPlanShutdown){
                if (value === '') {
                    callback(new Error('请选择订单号'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validateEquipmentRunningHours = (rule,value,callback) => {
            const isPlanShutdown = this.isPlanShutdown;
            if(!isPlanShutdown){
                callback();
            } else {
                callback();
            }
        }
        return {
            userInfo:{
                username:"",
                userId:"",
                userPhone:"",
                user:""
            },
            workShop:1,  //车间 机加工、走心机
            workShopProcess:"",
            formData:{
                materialCode:"",
                materialName:"",
                materialList:[],
                productOrder:"",
                productOrderList:[],
                equipment:"",
                gid:"",
                equipmentList:[],
                finishedNum:'',
                unQualifiedNum:'',
                materialAndProductInfoList:[],
                planNumber:"",
                classes:"",
                classesList:[],
                downtime:"",
                datetime:new Date(),
                downtReason:"",
                downtHours:"",
                downtReasonList:["缺刀具","缺料","刀具异常","等待换型","设备故障","产品换型"],
                attendanceHours:11,
                downtReasonList:[],
                equipmentRunningHours:"",
                singleShiftWage:"",
                standardManpower:"",
                pieceRate:"",
                scrapField1:0,  //工废
                scrapField2:0,
                scrapField1Reason:'',
                scrapField2Reason:''
            },
            formDataRules:{
                materialCode:[{required:true, validator:validateMaterialCode, trigger: 'blur'}],
                productOrder:[{required:true, validator:validateProductOrder, trigger: 'blur'}],
                equipment:[{required:true, message:"请选择设备", trigger: 'blur'}],
                finishedNum: [{required:true, validator: validateFinishedNum, trigger: 'blur' }],  //完成数量
                unQualifiedNum:[{required:true, validator: validateUnQualifiedNum, trigger: 'blur' }],  //不合格数量
                classes:[{required:true, message:"请选择班次", trigger: 'blur'}],
                datetime: [{ required: true, message: '请选择报工时间', trigger: 'blur'}],
                attendanceHours: [{ required: true, message: '出勤工时不能为空', trigger: 'blur'}],
                equipmentRunningHours: [{required: false, validator:validateEquipmentRunningHours, trigger: 'blur'}]
            },
            isPlanShutdown:false,
            confirmButtonLoading:false,
            remainingQuantity:0,  //完成数量 - 工单剩余计划数
            workreportButtonText:'报工',
            teamInfo:{
                teamRoleNum:null,
                teamName:""
            },
            //机加工 工废 料废
            jjg_waste_gf:['换型','换刀','崩刀','断刀','过切','装夹不良','落地件','工废','大小边','其它'],
            jjg_waste_lf:[],
            //走心机 工废 料废
            zxj_waste_gf:['换刀','换型','冷热机','尺寸','铁屑划伤','崩刀','来料不良','工程打样','其它'],
            zxj_waste_lf:['来料表面伤','材料开裂','棒料弯曲','棒料大小不合格','其它'],
            //装配车间 工废 料废
            zp_waste_gf:['打码','压装','焊接','铆接','调机','返修','外协','其它'],
            zp_waste_lf:['大小边','砂眼','外协','未光到','裂纹','卡滞','尺寸','其它'],
        };
    },
    mounted(){
        this.getDeviceList();
        this.getClassList();
        //this.getWareHouseInfo();
        //精致平台获取用户信息可能不准,此函数需要延迟调用
        setTimeout(()=> {
            this.getUserInfo();
            //this.getClassTeamList();
            this.getUserClassInfo();
        },500)
        this.checkTeamInfo();
        const isDevelopment = process.env.NODE_ENV === 'development';
        if(!isDevelopment){
            //精致环境下进行自动转屏
            autoOrientation();
        }
    },
    computed:{
        qualifiedNum(){
            let finishedNum = this.formData.finishedNum;
            let unQualifiedNum = this.formData.unQualifiedNum;
            if( finishedNum !== '' && unQualifiedNum !== '' && parseInt(unQualifiedNum) >= 0 && parseInt(finishedNum) >= parseInt(unQualifiedNum)){
                return parseInt(finishedNum) - parseInt(unQualifiedNum);
            }
            return '';
        },
        //订单列表信息
        productOrderList(){
            let code = this.formData.materialCode;
            let list = this.formData.materialAndProductInfoList;
            return list.filter(v => v.materialCode === code).map(k => {
                return {productOrderNumber:k.productOrderNumber,planQuantity:k.planQuantity, unqualifiedCount:k.unqualifiedCount};
            })
        },
        downtReasonBtnInfo(){
            const downtReasonList = this.formData.downtReasonList;
            let tip = "点击填写";
            if(downtReasonList.length > 0){
                for(let i = 0; i < downtReasonList.length; i ++){
                    if(Number(downtReasonList[i].downtimeDuration) > 0){
                        tip = "点击修改";
                        return tip;
                    }
                }
                return tip;
            } else {
                return tip;
            }
        },
        wasteList_gf(){
            const workShop = this.workShop;
            if(workShop == 1){
                return this.jjg_waste_gf;
            } else if(workShop == 2){
                return this.zxj_waste_gf;
            } else {
                return [];
            }
        },
        wasteList_lf(){
            const workShop = this.workShop;
            if(workShop == 1){
                return this.jjg_waste_lf;
            } else if(workShop == 2){
                return this.zxj_waste_lf;
            } else {
                return [];
            }
        }
    },
    watch:{
        //监听物料选择的变化
        "formData.materialCode":{
            handler(newVal, oldVal){
                if(newVal !== oldVal && newVal !== ""){
                    this.formData.productOrder = "";
                    let arr = this.formData.materialList.filter(item => item.materialCode === this.formData.materialCode);
                    if(arr.length > 0){
                        this.formData.materialName = arr[0].materialName;
                    }
                    if((this.workShop == 1 && this.workShopProcess) || this.workShop == 2){
                        this.getOeeInfoByProductModel();
                    }
                }
                if(newVal === ""){
                    this.formData.materialName = "";
                    // this.getMaterialInfoAndProductInfo();
                }
            }
        },
        //监听订单的选择
        "formData.productOrder":{
            handler(newVal, oldVal){
                if(newVal !== oldVal && newVal !== ""){
                    //获取订单中的计划数量
                    let orderInfo = this.productOrderList.filter(item => item.productOrderNumber === this.formData.productOrder)[0];
                    this.formData.planNumber = orderInfo.planQuantity;
                }
                if(newVal === ""){
                    this.formData.planNumber = "";
                }
            }
        },
        //监听设备的选择
        "formData.equipment":{
            handler(newVal, oldVal){
                if(newVal !== "" && newVal !== oldVal){
                    //获取所选设备所在车间名称
                    this.formData.gid = this.formData.equipmentList.filter(item => item.deviceCode === this.formData.equipment)[0].gid;
                    console.log(this.formData.gid);
                    //清空数据
                    this.formData.productOrder = "";
                    this.formData.planNumber = "";
                    this.formData.materialCode = "";
                    this.getMaterialInfoAndProductInfo();
                }
                if(newVal === ""){
                    this.getDeviceList();
                    this.formData.materialCode = "";
                    this.formData.productOrder = "";
                    this.formData.materialList = [];
                    this.formData.productOrderList = [];
                }
            }
        },
        //监听车间 机加工/走心机的选择
        workShop:{
            handler(newVal,oldVal){
                this.formData.equipment = "";
                this.getDeviceList();
                this.getDefaultSalary();
                this.workShopProcess = "";
                this.formData.equipmentRunningHours = 0;
                this.formData.standardManpower = 0;
                this.formData.pieceRate = 0;
                this.formData.scrapField1Reason = "";
                this.formData.scrapField2Reason = "";
            },
            immediate:true
        },
        isPlanShutdown:{
            handler(newValue,oldValue){
                this.planShutdownEvent();
            }
        },
        "workShopProcess":{
            handler(newVal,oldVal){
                this.formData.equipmentRunningHours = 0;
                this.formData.standardManpower = 0;
                this.formData.pieceRate = 0;
                if(newVal && this.formData.materialCode){
                    this.getOeeInfoByProductModel();
                }
            }
        }
    },
    methods: {
        //获取当前用户信息
        async getUserInfo () {
            reqUserInfo().then(res => {
                if(res.data.code === 200){
                    this.userInfo.username = res.data.data.nickname;
                    this.userInfo.userId = res.data.data.id;
                    this.userInfo.userPhone = res.data.data.mobile;
                    this.userInfo.user = res.data.data.username;
                }
                console.log("获取当前用户信息",res);
            }).catch(err => {
                console.log('请求当前用户信息失败,即将解析本地token...');
                this.getUserInfoByToken();
            })
        },
        getUserInfoByToken(){
            const userInfo = getUserInfoByToken();
            const { name,preferred_username,email} = userInfo;
            this.nickname = name || "";
            this.userId = "";
            this.userPhone = email.split("@")[0];
            this.username = preferred_username || "";
            console.log('本地解析token获取用户信息===> nickname:' + this.nickname + " userId:" + this.userId + " userPhone:" + this.userPhone + " username:" + this.username);
            if(this.nickname === "" && this.username === ""){
                Dialog.confirm({title:'提示',message:'未获取到用户信息，请重试'}).then(confirm => {
                    this.getUserInfo();
                })
            }
        },
        //查询当天的订单信息获取物料信息
        async getProductOrderOfDay () {
            reqProductOrderOfDay(this.formatDate(new Date(),3)).then(res => {
                if(res.data.code === 200){
                    //过滤出当天订单的物料名称
                    let array = res.data.data.content.filter(item => {
                        if(item.productOrderMaterials){
                            if(item.productOrderMaterials.length > 0){
                                if(item.productOrderMaterials[0].materialFields){
                                    if(item.productOrderMaterials[0].materialFields.code){
                                        return true;
                                    } else {
                                        return false
                                    }
                                } else {
                                    return false;
                                }
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    })
                    let list = array.map(item => {
                        return {code:item.productOrderMaterials[0].materialFields.code,id:item.productOrderMaterials[0].materialFields.id,name:item.productOrderMaterials[0].materialFields.name};
                    })
                    const seen = new Set();
                    let arr = list.filter(item => {
                        const duplicate = seen.has(item.id);
                        seen.add(item.id);
                        return !duplicate;
                    })
                    this.formData.materialList = arr;
                }
                console.log('查询当天的订单信息',res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //选择号物料后查询订单信息
        async getProductOrderList () {
            let materialCode = this.formData.materialList.filter(item => item.code === this.formData.materialName)[0].code;
            if(materialCode === "") return ;
            reqProductOrderList(materialCode).then(res => {
                if(res.data.code === 200){
                    this.formData.productOrderList = res.data.data.content;
                }
                console.log("通过物料编码/品名查询订单信息",res);
            }).catch(err => {
                this.$message({type:"error",message:"订单信息获取失败"});
            })
        },
        //获取设备列表信息
        async getDeviceList () {
            let workshop = this.workShop === 1 ? 143533 : 143532;
            getDeviceAPI(workshop).then(res => {
                if(res.data.code === 200){
                    this.formData.equipmentList = res.data.data.map(item => {
                        return {deviceId:item.deviceId, deviceCode:item.deviceCode, deviceName:item.deviceName, gid:item.gid, gname:item.gname};
                    });
                }
                console.log('获取设备列表信息',res);
            }).catch(err => {
                console.log('获取设备列表信息',err);
                Dialog.confirm({title:'提示',message:'设备列表获取失败,点击确定按钮重试'}).then(confirm => {
                    this.getDeviceList();
                })
            })
        },
        //获取班次信息
        async getClassList() {
            reqClassesList().then(res => {
                if(res.data.code === 200){
                    this.formData.classesList = res.data.data;
                }
                console.log('获取班次信息',res);
            }).catch(err => {
                console.log('获取班次信息失败',err);
                console.log('获取班次信息失败，即将赋值默认班次数据...');
                this.formData.classesList = [{id:1,shiftType:'白班'},{id:2,shiftType:'晚班'}];
            })
        },
        //查询当前选择设备所在车间的订单及物料信息
        async getMaterialInfoAndProductInfo () {
            let gid = this.formData.gid;
            console.log('设备所在车间',gid);
            if(!gid) {
                this.formData.materialList = [];
                this.formData.productOrderList = [];
                return;
            }
            reqMaterialInfoAndProductInfoByGid(gid).then(response => {
                if(response.status === 200){
                    this.formData.materialAndProductInfoList = response.data;

                    let temp  = response.data.map(item => {
                        return {materialCode:item.materialCode,materialName:item.materialName};
                    });
                    this.formData.materialList = temp.filter((item,index,self) => {
                        return self.findIndex(t => t.materialCode === item.materialCode) === index;
                    })
                    console.log('获取设备所在车间品名数据',temp,this.formData.materialList);
                    // this.formData.productOrderList = response.data.map(item => {
                    //     return {productOrderNumber:item.productOrderNumber,planQuantity:item.planQuantity, unqualifiedCount:item.unqualifiedCount};
                    // })
                }
                console.log('通过设备所在车间获取订单和物料信息',response);
            }).catch(err => {
                this.$message({type:"error",message:"当前设备车间订单物料信息获取失败"})
            })
        },
        //保存、取消按钮
        async save_btn(){
            /* if(this.userInfo.classTeamList.length === 0){
                this.$message({type:"info",message:"未获取到班组信息不能进行报工"});
                return;
            }
            //管理员不能报工
            if(this.userInfo.classTeamList.length > 1){
                this.$message({type:"info",message:"管理员用户不能进行报工"});
                return;
            } */
            if(this.teamInfo.teamRoleNum == -1){
                Dialog({title:'提示',message:'您未在班组成员中，请联系管理员添加您至班组成员后再进行报工'});
                return;
            }
            if(this.teamInfo.teamRoleNum == 2){
                Dialog({title:'提示',message:'管理员用户不能报工'});
                return;
            }
            if(!(this.teamInfo.teamRoleNum == 0 || this.teamInfo.teamRoleNum == 1)){
                Dialog({title:'提示',message:'当前用户班组类别不属于班组长或者班组成员，不能进行报工'});
                return;
            }
            //停机时长大于设备运行时长不能报工
            if(this.formData.downtReasonList.reduce((pre,cur) => pre + Number(cur.downtimeDuration),0) > Number(this.formData.equipmentRunningHours)){
                this.$alert("设备停机时长不能大于运行时长",'提示',{confirmButtonText:"确定",callback:action => {}});
                return ;
            }
            let workShop = this.workShop;
            let workShopProcess = workShop === 1 ? this.workShopProcess : 6;
            if(workShop === "") return this.$message({type:"info",message:"请选择车间类型!"});
            console.log(workShopProcess);
            if(workShop === 1 && workShopProcess == "") return this.$message({type:"info",message:"请选择工序!"});
            let validateResult1 = false;
            let validateResult2 = false;
            this.$refs.leftForm.validate((valid) => {
                if (valid) {
                    validateResult1 = true;
                } else {
                    validateResult1 = false;
                    return false;
                }
            });
            this.$refs.rightForm.validate((valid,list) => {
                if (valid) {
                    validateResult2 = true;
                } else {
                    validateResult2 = false;
                    if(list.classes){
                        this.$confirm("当前用户所在班组未查询到排班信息，请联系管理人员在排班小程序上进行排班后再报工", '提示', { type: 'warning'});
                    }
                    return false;
                }
            });
            if(!(validateResult1 && validateResult2)) return ;
            this.confirmButtonLoading = true;
            //获取节拍信息
            if(!this.isPlanShutdown){
                const { equipmentRunningHours,standardManpower,pieceRate } = this.formData;
                if(equipmentRunningHours == 0 && standardManpower == 0 && pieceRate == 0){
                    try {
                        await this.getOeeInfoByProductModel();
                        const { equipmentRunningHours,standardManpower,pieceRate } = this.formData;
                        if(equipmentRunningHours == 0 && standardManpower == 0 && pieceRate == 0){
                            this.confirmButtonLoading = false;
                            const tmp = this.workShopProcess;
                            const model = this.formData.materialCode + (tmp === 3 ? "-A" : (tmp === 4 ? "-D" : (tmp === 7 ? "-E" : "")));
                            this.$alert(`该产品型号${model}没有添加节拍信息，请联系管理人员添加节拍信息后再报工`,'提示',{confirmButtonText:"确定",callback:action => {}});
                            return;
                        }
                    } catch (error) {
                        this.confirmButtonLoading = false;
                        return;
                    };
                }
            }
            if(!this.isPlanShutdown){
                let restNum = 0;  //当前订单剩余计划数量
                try {
                    restNum = await this.getOrderResidueCount();
                } catch (error) {
                    this.confirmButtonLoading = false;
                    return;
                }
                const { productOrder, datetime, planNumber, workShop,workShopProcess, finishedNum, unQualifiedNum } = this.formData;
                if(Number(finishedNum) > Number(restNum)){
                    this.$confirm(`完成数量(${finishedNum})大于当前订单剩余的计划数量(${restNum})，是否进行多张工单报工(当前工单完成数量将置为剩余计划数量,多余完成数量将转移至下一工单)?`, '提示', { confirmButtonText: '进行多张工单报工',cancelButtonText: '取消报工',type: 'warning'}).then(async () => {
                        await this.saveWorkOrder(restNum);
                        //继续报下一张工单
                        this.remainingQuantity = Number(finishedNum) - Number(restNum);
                        this.formData.materialAndProductInfoList = this.formData.materialAndProductInfoList.filter(v => v.productOrderNumber !== productOrder);
                        const orderList = this.productOrderList;
                        this.formData.productOrder = orderList.length > 0 ? orderList[0].productOrderNumber : "";
                        this.formData.finishedNum = this.remainingQuantity;
                        unQualifiedNum > restNum ? this.formData.unQualifiedNum = unQualifiedNum - restNum : this.formData.unQualifiedNum = 0;
                        this.workreportButtonText = "继续报工";
                        this.confirmButtonLoading = false;
                    }).catch((error) => {
                        this.$message({type: 'info',message: '已取消报工'});
                        this.confirmButtonLoading = false;   
                    });
                } else {
                    try {
                        await this.saveWorkOrder();
                        this.cancel_btn();
                        this.workreportButtonText = "报工";
                        this.confirmButtonLoading = false;
                    } catch (error) {
                        this.confirmButtonLoading = false;
                    }
                }
            }
            if(this.isPlanShutdown){
                try {
                    await this.saveWorkOrder();
                    this.cancel_btn();
                    this.confirmButtonLoading = false;
                } catch (error) {
                    this.confirmButtonLoading = false;
                }
            }     
        },
        cancel_btn(){
            this.formData.equipment = "";
            this.formData.materialCode = "";
            this.formData.productOrder = "";
            this.formData.finishedNum = "";
            this.formData.unQualifiedNum = "";
            this.formData.planNumber = "";
            this.formData.scrapField1 = 0;
            this.formData.scrapField2 = 0;
            
            this.formData.materialName = "";           
            this.formData.datetime = new Date();
            this.workShop = 1;
            this.workShopProcess = "";
            this.formData.downtReason = "";
            this.formData.downtHours = "";
            //停机时长置0
            this.formData.downtReasonList.forEach(k => {
                k.downtimeDuration = "";
            })
            this.formData.scrapField1 = 0
            this.formData.scrapField1Reason = "",
            this.formData.scrapField2 = 0;
            this.formData.scrapField2Reason = "";
        },
        saveWorkOrder(remainingPlanNum = null){
            return new Promise((resolve,reject) => {
                let workShopProcess = this.workShop === 1 ? this.workShopProcess : 6;
                let workShopProcessName = "";
                switch (workShopProcess) {
                    case 2:
                        workShopProcessName = "热处理";
                        break;
                    case 3:
                        workShopProcessName = "车床";
                        break;
                    case 4:
                        workShopProcessName = "铣床";
                        break;
                    case 5:
                        workShopProcessName = "清洗机";
                        break;
                    case 6:
                        workShopProcessName = "走心机";
                        break;
                    case 7:
                        workShopProcessName = "倒角";
                        break;
                    default:
                        break;
                }
                const { materialName,materialCode, productOrder, equipment, finishedNum, unQualifiedNum, planNumber, classes, datetime, attendanceHours, downtReasonList, equipmentRunningHours, singleShiftWage, standardManpower, pieceRate, scrapField1, scrapField2,scrapField2Reason,scrapField1Reason } = this.formData;
                const calNum = {
                    completedQuantity: remainingPlanNum === null ? finishedNum : remainingPlanNum,
                    qualifiedQuantity: remainingPlanNum === null ? (finishedNum - unQualifiedNum) : ((remainingPlanNum - unQualifiedNum < 0) ? 0 : (remainingPlanNum - unQualifiedNum)),
                    unqualifiedQuantity: remainingPlanNum === null ? unQualifiedNum : ((remainingPlanNum - unQualifiedNum < 0) ? remainingPlanNum : unQualifiedNum)
                };
                let paramsObj = {
                    productCode:materialCode,
                    productName:materialName,
                    workReportType:workShopProcessName,  //报工类型 0-装配线 1-Epc 2-热处理 3-车床..
                    workReportCode:workShopProcess,
                    productNumber:productOrder,
                    plannedQuantity:planNumber,
                    completedQuantity:calNum.completedQuantity,
                    qualifiedQuantity:calNum.qualifiedQuantity,
                    unqualifiedQuantity:calNum.unqualifiedQuantity,
                    attendanceHours:attendanceHours,
                    reportDate:this.formatDate(datetime,1),
                    operatorId:this.userInfo.userId,
                    operator:this.userInfo.username,
                    operatorPhone:this.userInfo.userPhone,
                    username:this.userInfo.user,
                    reviewStatus:0,  //审核状态 0-未审核 1-驳回 2-审核通过
                    classes:classes,
                    classesTime:this.formData.classesList.filter(item => item.shiftType === classes)[0].workTime,
                    machine:this.formData.equipmentList.filter(item => item.deviceCode === equipment)[0].deviceName,
                    machineCode:equipment,
                    workShop:this.workShop === 1 ? '机加工' : '走心机',  //车间类型 0-装配线 1-机加工 2-走心机
                    workShopCode:this.workShop,
                    productionProcessList:[],
                    processMaterialList:[],
                    appealStatus:0,
                    appealRemark:"",
                    inspectionPerson:"",
                    inspectionPersonCode:"",
                    warehouseCode:"",
                    warehouseId:"",
                    teamName:this.teamInfo.teamName,
                    downtimeReportlList:downtReasonList,
                    pieceRate:pieceRate,
                    singleShiftWage:singleShiftWage,
                    standardManpower:standardManpower,
                    operatingTime:equipmentRunningHours,
                    allowRepeated:remainingPlanNum === null ? (this.workreportButtonText == "继续报工" ? 1 : 0) : 1,
                    laborCostQuantity:scrapField1,
                    workScrapReason:"",
                    materialScrapQuantity:scrapField2,
                    materialScrapReason:""
                };
                reqSaveData(paramsObj).then(response => {
                    if(response.data.code === 200){
                        const img1 = require("../../assets/image/smilingface.png");
                        const img2 = require("../../assets/image/cryingface.png");
                        if(paramsObj.completedQuantity >= paramsObj.plannedQuantity){
                            this.$alert(`<div style='display:flex;align-items:center;'><img src=${img1} style='width:50px;height:50px;margin-right:10px;'><span>报工完成</span></div>`, '提示', {
                                dangerouslyUseHTMLString: true
                            });
                        } else {
                            this.$alert(`<div style='display:flex;align-items:center;'><img src=${img2} style='width:50px;height:50px;margin-right:10px;'><span>产出未达成,请再接再厉!</span></div>`, '提示', {
                                dangerouslyUseHTMLString: true
                            });
                        }
                        resolve("报工数据保存成功");
                    }
                    console.log("保存数据api",response);
                    reject(response);
                }).catch(error => {
                    this.$alert("报工失败:"+ error.response.data.message,'提示',{confirmButtonText:"确定",callback:action => {}});
                    console.log("保存数据api",error);
                    reject(error);
                });
            })
        },
        //格式化时间
        formatDate(val,type){
            let date = new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type === 0){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 1){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day);
            } else if (type === 2){
                return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 3){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
            }
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        },
        //点击扫码
        async sweep_btn(type){
            try {
                let res = await qrCode();
                switch (type) {
                    case 'equipment':
                        this.formData.equipment = res;
                        this.findEquipmentByDeviceCode(res);
                        break;
                    default:
                        break;
                }
                console.log('调用精致提供的扫码api',res);
            } catch (error) {
                this.$message({type:"warning",message:error});
            }
        },
        //品名搜索
        remoteMethod(materialCode){
            if(materialCode.trim() === "") {
                this.getMaterialInfoAndProductInfo();
                return;
            }
            reqMaterialsInfo(materialCode).then(response => {
                if(response.data.code === 200 && response.data.data !== null){
                    let { code, id, name } = response.data.data.materialFields;
                    this.formData.materialList = [{materialCode:code,materialId:id,materialName:name}];
                }
                if(response.data.code === 200 && response.data.data === null){
                    this.formData.materialList = [];
                }
                console.log('根据物料编号查询物料',response);
            }).catch(error => {
                this.$message({type:"error",message:error});
            })
        },
        //查找设备
        findEquipmentByDeviceCode (val) {
            if(val.trim() === "") return;
            reqDeviceInfo(val).then(res => {
                if(res.data.code === 200){
                    this.formData.equipmentList = res.data.data.content.map(item => {
                        return {deviceId:item.deviceId, deviceCode:item.deviceCode, deviceName:item.deviceName, gid:item.gid, gname:item.gname};
                    });
                }
                console.log('获取设备信息,通过设备编号',res);
            }).catch(err => {
                this.$message({type:"error",message:"设备查询出错"});
            })
        },
        //获取班组列表信息
        getClassTeamList() {
            reqClassTeamList().then(res => {
                if(res.data.code === 200){
                    this.userInfo.classTeamList = res.data.data.map(item => item.teamName);
                }
            }).catch(error => {
                this.$message({type:"error",message:"获取班组列表信息出错"});
            })
        },
        //查询仓库信息
        getWareHouseInfo() {
            reqWareHouseInfo().then(response => {
                if(response.status === 200){
                    this.formData.incomingTypeList = response.data.map(item => {
                        return {code:item.warehouseCode,name:item.warehouseName,id:item.warehouseId}
                    })
                }
                console.log("获取仓库信息",response);
            }).catch(error => {
                this.$message({type:"error",message:error})
            })
        },
        wirteDowntReason(){
            this.$refs.downtReason.dialogFormVisible = true;
        },
        downtReasonClose(parameter){
            this.formData.downtReasonList = parameter;
        },
        validateInput(bindDataName) {
            const inputValue = this.formData[bindDataName];        
            //输入正实数，小数只能有一位
            const regex = /^(?!00)\d+(\.\d{0,1})?$/;
            if (!regex.test(inputValue) && inputValue !== '') {
                this.formData[bindDataName] = inputValue.slice(0, -1);
            }
        },
        //获取单班工资默认值
        async getDefaultSalary(){
            let defaultSalary = 0;
            let workshop = this.workShop === 1 ? "机加工" : "走心机";
            reqDefaultSalary().then(response => {
                if(response.data.code === 200){
                    const tmp = response.data.data;
                    for(let i = 0; i < tmp.length; i ++){
                        if(tmp[i].configKey == workshop){
                            defaultSalary = tmp[i].configValue;
                            break;
                        }
                    }
                }
                this.formData.singleShiftWage = defaultSalary;
                console.log('获取单班工资api',response);
            }).catch(error => {
                console.log('获取单班工资api异常',error);
                console.log("获取单班工资异常,即将设定单班工资初始值0...");
                this.formData.singleShiftWage = 0;
            })
        },
        async getOeeInfoByProductModel(){
            return new Promise((resolve,reject) => {
                const workShopProcess = this.workShopProcess;
                let materialCode = this.formData.materialCode;
                if(workShopProcess === 3){
                    materialCode = materialCode + "-A";
                } else if (workShopProcess === 4){
                    materialCode = materialCode + "-D";
                } else if (workShopProcess === 7) {
                    materialCode = materialCode + "-E";
                }
                //车床 + A  铣床 D  倒角E
                if(materialCode === ""){
                    return;
                }
                this.formData.equipmentRunningHours = 0;
                this.formData.standardManpower = 0;
                this.formData.pieceRate = 0;
                reqOeeInfoByProductModel(materialCode).then(response => {
                    if(response.data.code === 200 && response.data.data){
                        const { pieceRate, standardManpower, operatingTime } = response.data.data;
                        this.formData.pieceRate = pieceRate || 0;
                        this.formData.standardManpower = standardManpower || 0;
                        this.formData.equipmentRunningHours = operatingTime || 0;
                    } else {
                        this.formData.equipmentRunningHours = 0;
                        this.formData.standardManpower = 0;
                        this.formData.pieceRate = 0;
                    }
                    console.log('通过产品型号获取节拍对象信息api',response);
                    resolve();
                }).catch(error => {
                    this.$alert("请求产品节拍信息出错:" + error.response?.data?.message + "。网络波动，尝试切换网络并重新打开小程序~",'提示',{confirmButtonText:"确定",callback:action => {}});
                    console.log('通过产品型号获取节拍对象信息api',error);
                    reject(new Error(error));
                })
            })
        },
        planShutdownEvent(){
            const isPlanShutdown = this.isPlanShutdown;
            const formData = this.formData;
            if(isPlanShutdown){
                formData.materialCode = "";
                formData.materialName = "";
                formData.productOrder = "";
                formData.finishedNum = 0;
                formData.unQualifiedNum = "";
                formData.planNumber = "";
                formData.downtReasonList = [];
                formData.equipmentRunningHours = "";
                formData.singleShiftWage = "";
                formData.standardManpower = "";
                formData.pieceRate = "";
                formData.attendanceHours = 0;
            } else {
                formData.finishedNum = "";
            }
        },
        //获取当前订单剩余计划数量
        async getOrderResidueCount(){
            return new Promise(async (resolve,reject) => {
                const { productOrder, datetime, planNumber, finishedNum, unQualifiedNum } = this.formData;
                const parameters = {productNumber:productOrder,workReportCode:(this.workShop == 1 ? this.workShopProcess : 6),reportDate:datetime,plannedQuantity:planNumber};
                //测试检查参数
                if(!(parameters.productNumber && parameters.workReportCode && parameters.reportDate && parameters.plannedQuantity)){
                    this.$alert(`请求订单剩余计划参数出错，参数:${parameters.productNumber}-${parameters.workReportCode}-${parameters.reportDate}-${parameters.plannedQuantity}。网络波动，尝试切换网络并重新打开小程序~`,'提示',{confirmButtonText:"确定"});
                    reject();
                    return ;
                }
                reqOrderResidueCount(parameters).then(response => {
                    if(response.data && response.data.code === 200 && response.data.data){
                        const restNum = response.data.data;
                        resolve(restNum);
                        return;
                    }
                    resolve(0);
                },error => {
                    console.log('请求订单剩余计划数量api',error);
                    this.$alert("请求订单剩余计划数量出错:" + error.response?.data?.message + "。网络波动，尝试切换网络并重新打开小程序",'提示',{confirmButtonText:"确定",callback:action => {}});
                    reject(new Error(error));
                })
            });
        },
        //校验设备运行时长输入
        validateInputEquipmentRunningHours() {
            const inputValue = this.formData.equipmentRunningHours;
            //const regex = /^\d+(\.\d{0,1})?$/;
            const regex = /^(?!00)\d+(\.\d{0,1})?$/;
            if (!regex.test(inputValue) && inputValue !== '') {
                this.formData.equipmentRunningHours = inputValue.slice(0, -1);
            }
        },
        //获取当前用户的班次信息
        getUserClassInfo(){
            const { name,preferred_username,email} = getUserInfoByToken();
            reqUserClassInfo(preferred_username).then(response => {
                if(response.data.code === 200 && response.data.data){
                    const { teamId,teamName,shiftId,shiftName } = response.data.data;
                    this.formData.classes = response.data.data.shiftName;
                    this.teamInfo.teamName = teamName;
                } else {
                    this.$confirm("当前用户所在班组未查询到排班信息，请联系管理人员在排班小程序上进行排班后再报工", '提示', { type: 'warning'});
                }
                console.log('获取用户班次信息api',response);
            },error => {
                this.$confirm("获取当前用户班次信息出错(将会影响报工),点击确定重新请求", '提示', { type: 'warning'}).then(confirm => {
                    this.getUserClassInfo();
                })
                console.log('获取用户班次信息api',error.response);
            })
        },
        //判断用户类别 2-管理员 1-班组长 0-组员 -1非成员
        checkTeamInfo() {
            reqCheckIsTeam().then(res => {
                if(res.data.code === 200){
                    const teamRoleNum = res.data.data;
                    this.teamInfo.teamRoleNum = teamRoleNum;
                }
                console.log('判断当前用户类别',res);
            }).catch(err => {
                this.teamInfo.teamRoleNum = null;
                Dialog.confirm({title:'提示',message:'用户类别请求失败(将会影响报工)，点击确定按钮重试'}).then(confirm => {
                    this.checkTeamInfo();
                })
            })
        }
    },
}
</script>
  
<style lang="scss" scoped>
  .workorder{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    user-select: none;
    overflow: auto;
    .page-head{
        width: 100%;
        flex: 0.5;
        padding: 0 5%;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #4095e5;
        color: white;
        font-size: 14px;
        min-height: 40px;
    }
    @media screen and (min-width:300px) and (max-width:600px) {
        .page-head{
            width: 100%;
            height: 80px;
            align-items: flex-end;
            padding: 1% 5%;
            min-height: 100px;
        }
    }
    .page-main{
        width: 100%;
        flex: 5;
        display: flex;
        flex-wrap: wrap;
        padding: 0 3% 0 3%;
        justify-content: space-between;
        box-sizing: border-box;
        .main-left{
            box-sizing: border-box;
        }
        .main-right{
            box-sizing: border-box;
        }
        @media screen and (min-width: 600px) {
            .main-left{
                width: 40%;
                height: 100%;
            }
            .main-right{
                width: 40%;
                height: 100%;
            }
        }
    }
    .page-radio{
        width: 100%;
        flex: 0.6;
        padding: 0.5% 3%;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        .radio-content{
            margin: 10px 0;
            display: flex;
            align-items: first baseline;
            .content-tip{
                width: 50px;
                margin-right: 15px;
                font-size: 14px;
            }
            .content-process{
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                .process-item{
                    margin-bottom: 5px;
                }
            }
        }
        .radio-info{
            width:100%;
            height: 30px;
            box-sizing: border-box;
            display: flex;
        }
    }
    .page-footer{
        width: 100%;
        flex: 1;
        display: flex;
        padding: 1% 0;
        justify-content: space-evenly;
        align-items: center;
        .footer-btn{
            width: 100px;
        }
    }
  }
  //表单项
  ::v-deep .form-item{
    width: 95%;
    .el-form-item__content{
        display: flex;
        align-items: center;
    }
  }
  .el-date-picker{
    width: 70%;
  }
</style>
<style lang="scss">
@media screen and (min-width:300px) and (max-width:600px) {
    .el-message-box{
        width:320px;
    }
}
</style>